import React, { Component } from "react";
import { apiGetOrderDetails, apiManageRefundRequest, apiFinishOrder } from "@/request/orderManagement";
import GoBack from "@/components/TheGoBack";
import { Table, Button, Modal, Form, InputNumber, Space, Descriptions } from "antd";
import "../style/style.less";
import {
  DownloadOutlined
} from '@ant-design/icons';
import TheImage from "@/components/TheImage";
import { toPrint, printWaybill } from '@/utils/toPrint'

class Details extends Component {
  FormRef = React.createRef()
  state = {
    dataSource: null,
    productType: true,
    frozenVisible: false,
    imageVisible: false,
    date: "",
    columns: [
      {
        title: "商品信息",
        width: 600,
        render: (text, record) => {
          let style = {
            width: 200,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis'
          }
          let label = ''
          switch (record.salesStatus) {
            case "1":
              label = "（退款中）"
              break
            case "0":
              label = "（退款失败）"
              break
            case "9":
              label = "（退款成功）"
              break
            default:
              label = ""
          }
          return (
            <div style={{ display: "flex", alignItems: "center" }}>
              <TheImage
                src={record.productImage}
                width={100}
              />
              <div style={{ margin: "0 10px" }}>{record.productName}{label ? label : ""}</div>
              <div>{record.sku}</div>
            </div>
          );
        },
      },
      {
        title: "商品单价",
        dataIndex: "orderPrice",
        key: "orderPrice",
        render: (text) => <React.$price price={text || 0} />,
      },
      {
        title: "商品数量",
        dataIndex: "orderProductCount",
        key: "orderProductCount",
        render: (text) => text || 0,
      },
      {
        title: "总计",
        dataIndex: "orderPriceTotal",
        key: "orderPriceTotal",
        render: (text) => <React.$price price={text || 0} />,
      },
    ],
  };

  async componentDidMount() {
    await this.getDetails();
  }

  getDetails = async () => {
    const orderId = this.props.match.params.id;
    const response = await apiGetOrderDetails({ orderId });
    if (response.code === 0) {
      const dataSource = response.data;
      let date = ""
      if (dataSource.orderInfoExpansionDto && dataSource.orderInfoExpansionDto.appointmentDate) {
        let appointmentDate = dataSource.orderInfoExpansionDto.appointmentDate
        JSON.parse(appointmentDate).map(item => {
          date += " " + item.date
        })
        this.setState({
          date
        })
      }

      let payWay = ''
      switch (dataSource.payWay) {
        case 'WeChat':
          payWay = '微信'
          break;
        case 'Alipay':
          payWay = '支付宝'
          break;
        case 'UnionPay':
          payWay = "银联"
          break;
        case 'YsPay':
          payWay = "银行卡支付"
          break;
        case 'RemoteAlipay':
          payWay = "扫码支付（支付宝）"
          break;
        case 'RemoteWeChat':
          payWay = "扫码支付（微信）"
          break;
        default:
          payWay = "未知支付方式"
      }
      let pickupWay = ""
      switch (dataSource.pickupWay) {
        case 'D':
          pickupWay = "到店自取"
          break;
        case 'T':
          pickupWay = '同城配送'
          break
        default:
          pickupWay = "/"
      }
      let orderState = ''
      switch (dataSource.orderState) {
        case '2':
          orderState = "未使用"
          break
        case '3':
          switch (dataSource.deliveryState) {
            case 'Y':
              orderState = '已派送'
              break
            case 'N':
              orderState = '待派单'
              break
            default:
              orderState = "未知订单状态"
          }
          break
        case '9':
          orderState = "已使用"
          break
        default:
          orderState = "未知订单状态"
      }
      const detailsData = [
        {
          title: "订单编号",
          value: dataSource.orderCode,
        },
        {
          title: "买家ID",
          value: dataSource.memberId,
        },
        {
          title: "支付方式",
          value: payWay,
        },
        {
          title: "订单金额",
          value: <React.$price price={dataSource.orderTotalPrice || 0} />,
        },
        // {
        //   title: "优惠券名称",
        //   value: couponTitle,
        // },
        // {
        //   title: "优惠金额",
        //   value: <React.$price price={dataSource.couponTotal || 0} />,
        // },
        {
          title: "实付金额",
          value: <React.$price price={dataSource.orderPayPrice || 0} />,
        },
        {
          title: "下单时间",
          value: dataSource.createTime,
        },
        {
          title: "买家昵称",
          value: dataSource.orderMemberName,
        },
        {
          title: "收货方式",
          value: pickupWay,
        },
        {
          title: "订单状态",
          value: orderState,
        },
        {
          title: "使用日期",
          value: dataSource.payTime,
        },
        {
          title: "获赠积分",
          value: dataSource.presentIntegral || 0,
        },
        {
          title: "导购员",
          value: dataSource.shoppingGuideName ? dataSource.shoppingGuideName : "/",
        }
      ];
      const orderDetailList = dataSource.orderDetailList.filter(v => {
        let productSkuJson = JSON.parse(v.productSkuJson)
        const { skuAttribute } = productSkuJson;
        if (!skuAttribute) {
          if (JSON.stringify(productSkuJson) === '{}')
            this.setState({
              columns: [
                {
                  title: "服务信息",
                  render: (text, record) => {
                    return (
                      <div style={{ display: "flex", alignItems: "center" }}>
                        <TheImage
                          src={record.productImage}
                          width={100}
                        />
                        <span style={{ margin: "0 10px" }}>{record.productName}</span>
                        <span>{record.sku}</span>
                      </div>
                    );
                  },
                },
                {
                  title: "美容师",
                  dataIndex: "shoppingBeauticianName",
                  key: "shoppingBeauticianName",
                  render: (text) => {
                    return text ? text : "/"
                  }
                },
                {
                  title: "服务单价",
                  dataIndex: "orderPrice",
                  key: "orderPrice",
                  render: (text) => <React.$price price={text || 0} />,
                },
                {
                  title: "服务数量",
                  dataIndex: "orderProductCount",
                  key: "orderProductCount",
                  render: (text) => text || 0,
                },
                {
                  title: "总计",
                  dataIndex: "orderPriceTotal",
                  key: "orderPriceTotal",
                  render: (text) => <React.$price price={text || 0} />,
                },
              ],
              productType: false
            })
          return {
            ...v,
            productSkuJson
          }
        }
        let resultSkuArr = skuAttribute.map(value => value.value)
        return {
          ...v,
          productSkuJson,
          sku: resultSkuArr.join(","),
        }
      })
      const productData = orderDetailList;
      const receiving = [
        {
          title: "收货人",
          value: dataSource.memberName,
        },
        {
          title: "联系电话",
          value: dataSource.memberPhone,
        },
        {
          title: "收货地址",
          value: dataSource.memberAddress,
        },
      ];
      this.setState({
        dataSource,
        detailsData,
        productData,
        receiving,
      });
    }
  };
  getOrderState = (value) => {
    let label = null;
    switch (value) {
      case "3":
        label = <span style={{ color: "#d9001b" }}>待付款</span>;
        break;
      case "4":
        label = <span style={{ color: "#f59a23" }}>待发货</span>;
        break;
      case "5":
        label = <span style={{ color: "#70b603" }}>待收货</span>;
        break;
      case "9":
        label = <span style={{ color: "#70b685" }}>交易成功</span>;
        break;
      case "0":
        label = <span style={{ color: "#c280ff" }}>交易关闭</span>;
        break;
      default:
        break;
    }
    return label;
  };
  getOrderStatus = (value) => {
    let num = 0;
    switch (value) {
      case "3":
        num = 0;
        break;
      case "4":
        num = 1;
        break;
      case "5":
        num = 2;
        break;
      case "9":
        num = 4;
        break;
      default:
        break;
    }
    return num;
  };
  WaybillPrint = () => {
    this.setState({
      frozenVisible: true
    }, () => {
      this.FormRef.current.setFieldValue('changePrice', React.$transNum(this.state.dataSource.orderPayPrice, 2, -2))
    })
  }
  bianli = (path) => {

    let filename;
    if (path.indexOf("/") > 0) //如果包含有"/"号 从最后一个"/"号+1的位置开始截取字符串
    {
      filename = path.substring(path.lastIndexOf("/") + 1, path.length);
    } else {
      filename = path;
    }
    return filename;
  }
  DownloadOutlined =async (urls, type) => {

    let name = this.bianli(urls)
    if (type == "1") {
      fetch(urls)
        .then(res => res.blob())
        .then(blob => {
          const a = document.createElement("a");
          const objectUrl = window.URL.createObjectURL(blob);
          a.download = name;
          a.href = objectUrl;
          a.click();
          window.URL.revokeObjectURL(objectUrl);
          a.remove();
        })
    } else if (type == "0") {
      let fileType = name.split('.')
     
      let resp = await fetch(urls).catch(e => {
        console.error(e)
      })
      if (!resp) {
        return
      }
      let eleA = document.createElement('a')
      let blob = await resp.blob().catch(e => {
        console.log(e)
      })
      if (!blob) {
        return
      }
      eleA.href = URL.createObjectURL(blob)
      eleA.download = name
      eleA.click()
    }
  }

  billSalePrint = () => {
    let { dataSource } = this.state
    let dataSourceObj = {
      orderCode: dataSource.orderCode,
      createTime: dataSource.createTime,
      storeName: dataSource.orderTypeName,
      memberName: dataSource.orderMemberName,
      memberPhone: dataSource.memberPhone,
      memberAddress: dataSource.memberAddress,
      orderTotalPrice: dataSource.orderTotalPrice,
      orderPayPrice: dataSource.orderPayPrice

    }
    let productData = dataSource.orderDetailList.map(item => {
      let productSkuJson = JSON.parse(item.productSkuJson)
      return {
        goodsName: item.productName,
        sku: productSkuJson.skuAttribute.map((j) => {
          return j.value
        }),
        giftId: item.giftId,
        orderProductCount: item.orderProductCount,
        orderPrice: item.orderPrice,
      }
    })
    console.log(dataSource, 'toPrint');
    toPrint(dataSourceObj, productData)
  }
  confirmComplete = () => {
    React.$confirm({
      title: '您确认要强制完结该订单吗？',
      onOk: async () => {
        const { orderId } = this.state.dataSource
        const response = await apiFinishOrder({ orderId });
        if (response.code === 0) {
          this.props.history.goBack()
        }
      },
    })
  }
  frozenVisibleCancel = () => {
    this.setState({
      frozenVisible: false,
    })
  }
  handleFinish = async (params) => {
    const { orderId } = this.state.dataSource
    const response = await apiManageRefundRequest({ orderId, refundAmount: React.$transNum(params.changePrice, 2, 2), remark: "" });
    if (response.code === 0) {
      this.props.history.goBack()
    }
  }
  //查看钥匙
  showKeys = (type) => {
    if (type == '1') {
      React.$confirm({
        title: '密码锁密码',
        content: this.state.dataSource.orderInfoExpansionDto.doorLockCode,
        okButtonProps: { style: { display: 'none' } },
      })
    } else if (type == '2') {
      let urls = this.state.dataSource.orderInfoExpansionDto.keyPath
      if (!urls ) {
        React.$message({
          type: 'info',
          content: `钥匙未上传`
        })
        return
      }
      this.setState({
        imageVisible: true,
      })
    }
  }
  showImageVisible = () => {
    this.setState({
      imageVisible: true
    })
  }
  ImageCancel = () => {
    this.setState({
      imageVisible: false
    })
  }

  render() {
    const { dataSource, imageVisible, detailsData, columns, productData, receiving, productType, frozenVisible, date } =
      this.state;
    return (
      <>
        <div className={"p-layout-box order-details-box"}>
          <GoBack history={this.props.history} title={"订单详情"} />
          {dataSource && (
            <div className={"p-layout-content"}>
              {
                dataSource.pickupWay == "T" && dataSource.orderState == 3 ? <div className='printBtn' >
                  <Button style={{ marginRight: 12 }} type="default" onClick={this.billSalePrint} >出货单打印</Button>
                  <Button type="default" onClick={this.WaybillPrint}>面单打印</Button>
                </div> : null
              }
              {['2', '3'].includes(dataSource.orderState) && dataSource.pickupWay == 'U' && <div style={{ display: 'flex', justifyContent: 'flex-end', margin: '20px 0' }}>
                <Button type="default" onClick={this.WaybillPrint} >退款</Button>
                <Button danger style={{ marginLeft: '20px' }} onClick={this.confirmComplete}>确认完成</Button>
              </div>}
              <div className={"order-details-content"}>
                <div className={"order-details-title"}>订单概况</div>
                <ul className={"order-details-information"}>
                  {detailsData.map((v, i) => {
                    return (
                      <li className={"order-details-information-item"}>
                        <span className={"item-title"}>{v.title}</span>
                        <span className={"item-separated"}>:</span>
                        <span className={"item-value"}>{v.value}</span>
                      </li>
                    );
                  })}
                </ul>
              </div>
              {productData.length > 0 ? <div className={"order-details-content"}>
                {productType ? <div className={"order-details-title"}>商品信息</div> : <div className={"order-details-title"}>服务信息</div>}
                <Table
                  dataSource={productData}
                  columns={columns}
                  pagination={false}
                  summary={(pageData) => {
                    let totalOrderPriceTotal = 0;
                    let totalOrderProductCount = 0;
                    pageData.forEach(
                      ({ orderPriceTotal, orderProductCount }) => {
                        totalOrderPriceTotal += orderPriceTotal || 0;
                        totalOrderProductCount += orderProductCount || 0;
                      }
                    );
                    return (
                      <>
                        <Table.Summary.Row>
                          <Table.Summary.Cell colSpan={4}>
                            {productType ? <div style={{ textAlign: "center" }}>
                              {`共${totalOrderProductCount}件商品，总计`}
                              <React.$price price={totalOrderPriceTotal || 0} />
                              元
                            </div> : <div style={{ textAlign: "center" }}>
                              {`共${totalOrderProductCount}项服务，总计`}
                              <React.$price price={totalOrderPriceTotal || 0} />
                              元
                            </div>}
                          </Table.Summary.Cell>
                        </Table.Summary.Row>
                      </>
                    );
                  }}
                />
              </div> : null}
              {productType ?
                <div className={"order-details-content"}>
                  <div className={"order-details-title"}>收货信息</div>
                  <ul className={"order-details-receiving"}>
                    {dataSource.pickupWay === 'T' ? receiving.map((v, i) => {
                      return (
                        <li key={i} className={"order-details-receiving-item"}>
                          <span className={"item-title"}>{v.title}</span>
                          <span className={"item-separated"}>:</span>
                          <span>{v.value}</span>
                        </li>
                      );
                    }) : <li className={"order-details-receiving-item"}>
                      <span className={"item-title"}>预留手机号</span>
                      <span className={"item-separated"}>:</span>
                      <span>{dataSource.orderRemark}</span>
                    </li>}
                  </ul>
                </div> : null}
              {dataSource && dataSource.orderInfoExpansionDto && <Descriptions >
                <Descriptions.Item label="联系人">{dataSource.memberName}</Descriptions.Item>
                <Descriptions.Item label="联系号码">{dataSource.memberPhone}</Descriptions.Item>
                <Descriptions.Item label="服务地址">{dataSource.memberAddress}</Descriptions.Item>
                <Descriptions.Item label="预约日期">{date}</Descriptions.Item>
                <Descriptions.Item label="钥匙存放方式">
                  {dataSource && dataSource.orderInfoExpansionDto && <Button onClick={() => this.showKeys(dataSource.orderInfoExpansionDto.keyStorageType)}>{["家中有人", "密码锁", "查看钥匙"][dataSource.orderInfoExpansionDto.keyStorageType]}</Button>
                  }                </Descriptions.Item>
                {dataSource && dataSource.orderInfoExpansionDto && <Descriptions.Item label="备注">{dataSource.orderInfoExpansionDto.remark}</Descriptions.Item>}
              </Descriptions>}
            </div>
          )}
          <Modal visible={frozenVisible} width="20%"
            onCancel={() => this.frozenVisibleCancel()}
            footer={null}
            title={'您确定要退款吗？'}
          >
            <Form
              labelCol={{
                span: 6,
              }}
              wrapperCol={{
                span: 14,
              }}
              ref={this.FormRef}
              onFinish={(values) => this.handleFinish(values)}
            >
              <Form.Item
                label={'退款金额'}
                name="changePrice"
                rules={[
                  {
                    required: true,
                    message: '请输入退款金额',
                  },
                ]}
              >
                <InputNumber placeholder={'请输入退款金额'} />
              </Form.Item>
              <Form.Item wrapperCol={{
                offset: 12,
                span: 16,
              }}>
                <Space size="small" style={{ marginLeft: 10 }}>
                  <Button type="default" onClick={() => this.frozenVisibleCancel()}>
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit">
                    确定
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Modal>
          <Modal visible={imageVisible}
            onCancel={() => this.ImageCancel()}
            footer={null}
            title={'钥匙位置'}
          >
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              {dataSource && dataSource.orderInfoExpansionDto && dataSource.orderInfoExpansionDto.fileType == "0" && <TheImage src={dataSource.orderInfoExpansionDto.keyPath} />}
              {dataSource && dataSource.orderInfoExpansionDto && dataSource.orderInfoExpansionDto.fileType == "1" && <video style={{ width: '200px', height: '200px' }} src={dataSource.orderInfoExpansionDto.keyPath} controls="controls" />}

              <DownloadOutlined style={{ fontSize: '28px', marginLeft: '20px' }} onClick={() => this.DownloadOutlined(dataSource.orderInfoExpansionDto.keyPath, dataSource.orderInfoExpansionDto.fileType)} />
            </div>
          </Modal>
        </div>
      </>
    );
  }
}

export default Details;
